import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import store2 from "store2";
import { request } from "@/utils/request.ts";

type UserState = {
  token: string;
  info: API.CurrentUser | null;
  menus: API.MenuObject[];
  permissions: string[];
};

// fetchLogin
export const fetchLogin = createAsyncThunk("user/fetchLogin", (data: any) => {
  // 调用接口，并返回
  return request.post<{
    token: string;
    expire: string;
    refreshToken: string;
    refreshExpire: string;
  }>("/admin/base/open/login", data);
});

// fetchPersonInfo
export const fetchPersonInfo = createAsyncThunk(
  "user/fetchPersonInfo",
  async () => {
    // 调用接口，并返回
    return await request.get<{
      info: API.CurrentUser;
      menus: API.MenuObject[];
    }>("/admin/base/comm/personInfo");
  }
);

const userSlice = createSlice({
  name: "user",
  initialState: {
    token: store2.get("token") || "", // 用户token
    info: null, // 用户信息
    menus: [], // 用户的菜单权限
    permissions: [], // 用户的按钮权限
  } as UserState,
  reducers: {},
  extraReducers: (builder) =>
    builder
      .addCase(fetchPersonInfo.fulfilled, (state, { payload }) => {
        state.info = payload.info;
        state.menus = payload.menus;
        state.permissions = payload.menus
          .filter((item: any) => item.type === 2)
          .map((item: any) => item.perms);
      })
      .addCase(fetchLogin.fulfilled, (state, { payload }) => {
        store2.set("token", payload.token);
        state.token = payload.token;
      }),
});

export default userSlice.reducer;
